package cn.hengzhu.main_manager.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hengzhu.main_manager.repository.dao.CaseAdvertiseFileMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCompMapper;
import cn.hengzhu.main_manager.repository.domain.CaseAdvertiseFile;
import cn.hengzhu.main_manager.repository.domain.CaseAdvertiseFileExample;
import cn.hengzhu.main_manager.repository.domain.ManageComp;
import cn.hengzhu.main_manager.repository.domain.ManageCompExample;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.repository.param.PageBaseParam;
import cn.hengzhu.main_manager.repository.vo.CaseAdvertiseFileVO;
import cn.hengzhu.main_manager.utils.AjaxResult;
import cn.hengzhu.main_manager.utils.AliOssUploadUtil;
import cn.hengzhu.main_manager.utils.LayUiResultJson;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.MoblieUrl;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;
import cn.hengzhu.main_manager.utils.config.AliOssConfig;


@Controller
@RequestMapping("/publishFile")
public class PublishAdvertisFileContorller {

	@Autowired
	private CaseAdvertiseFileMapper caseAdvertiseFileMapper;

	@Autowired
	private ManageCompMapper manageCompMapper;

	@Autowired
	private HttpServletRequest request;
	
	@MoblieUrl
	@RequestMapping("/index")
	public String index(Model model){
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		if(compId.equals(0)) {
			List<ManageComp> compList = manageCompMapper.selectByExample(new ManageCompExample());
			model.addAttribute("comps", compList);
		}
		model.addAttribute("compId", compId);
		return request.getAttribute("moblie")+"publishFile";

	}

	@MoblieUrl
	@RequestMapping("/add")
	public String add(Model model) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();

		ManageCompExample mce = new ManageCompExample();
		mce.setOrderByClause("CREATE_TIME desc");
		List<ManageComp> compList = new ArrayList<>();
		if (compId.equals(0)) {
			compList = manageCompMapper.selectByExample(mce);
		} else {
			mce.createCriteria().andCompIdEqualTo(compId);
			compList = manageCompMapper.selectByExample(mce);
		}

		model.addAttribute("compList", compList);
		return request.getAttribute("moblie")+"publishFileAdd";

	}

	@MoblieUrl
	@RequestMapping("/edit")
	public String edit(Model model, Integer fileId) {
		CaseAdvertiseFile selectByPrimaryKey = caseAdvertiseFileMapper.selectByPrimaryKey(fileId);
		Byte type = selectByPrimaryKey.getType();
		model.addAttribute("sign", type);
		return request.getAttribute("moblie")+"publishFileEdit";

	}

    
	@RequestMapping ("/upFile")
    @ResponseBody
    public Map<String ,String> upFile(HttpServletRequest request, MultipartFile file) throws IOException {
		Map<String ,String> map=new HashMap<>();
		String originalFilename = file.getOriginalFilename();
		String[] arr = originalFilename.split("\\.");

		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fileName = uuid + "." + arr[arr.length - 1];
		try {
			String upLoad = AliOssUploadUtil.upLoad(file,fileName);
			if(StringUtils.isNotBlank(upLoad)){
				map.put("code", "100");
				map.put("fileName", fileName);
			}else{
				map.put("code", "101");
			}
		} catch (Exception e) {
			map.put("code", "101");
		}
		return map;
    }
	

	/**
	 * @return 列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	public LayUiResultJson<CaseAdvertiseFileVO> list(PageBaseParam param,Integer compIdParam,Byte type) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<CaseAdvertiseFileVO> list = new ArrayList<>();
		PageHelper.startPage(param.getPage(), param.getLimit(), true);
		
		compId = (compId==0)?compIdParam:compId;
		List<CaseAdvertiseFile> caseAdvertiseFileList = caseAdvertiseFileMapper.selectByCompIdOrType(compId,type);
		
		PageInfo<CaseAdvertiseFile> pageInfo = new PageInfo<>(caseAdvertiseFileList);

		if (!caseAdvertiseFileList.isEmpty()) {

			List<Integer> compIdList = caseAdvertiseFileList.stream()
					.collect(Collectors.mapping(CaseAdvertiseFile::getCompId, Collectors.toList())).stream().distinct()
					.collect(Collectors.toList());
			ManageCompExample mce = new ManageCompExample();
			mce.createCriteria().andCompIdIn(compIdList);
			List<ManageComp> selectByExample = manageCompMapper.selectByExample(mce);
			Map<Integer, String> map = selectByExample.stream()
					.collect(Collectors.toMap(ManageComp::getCompId, ManageComp::getCompName));

			caseAdvertiseFileList.stream().forEach(a -> {
				CaseAdvertiseFileVO caseAdvertiseFileVO = new CaseAdvertiseFileVO();
				caseAdvertiseFileVO.setDes(a.getDes());
				caseAdvertiseFileVO.setCreatTime(a.getCreatTime());
				caseAdvertiseFileVO.setFileId(a.getFileId());
				caseAdvertiseFileVO.setName(a.getName());
				caseAdvertiseFileVO.setCompName(map.get(a.getCompId()));
				caseAdvertiseFileVO.setUrl(AliOssConfig.URL+a.getUrl());
				caseAdvertiseFileVO.setType(a.getType());
				list.add(caseAdvertiseFileVO);
			});

		}

		long count = pageInfo.getTotal();
		LayUiResultJson<CaseAdvertiseFileVO> result = new LayUiResultJson<>(count, list);
		return result;

	}

	/**
	 * @return 编辑
	 */
	@SystemControllerLog(description = "编辑广告资源")
	@RequestMapping("/editFile")
	@ResponseBody
	public AjaxResult editFile(CaseAdvertiseFile caseAdvertiseFile) {
		String url = caseAdvertiseFile.getUrl();
		if(StringUtils.isBlank(url)){
			caseAdvertiseFile.setUrl(null);
		}
		try {
			caseAdvertiseFileMapper.updateByPrimaryKeySelective(caseAdvertiseFile);
			return new AjaxResult();
		} catch (Exception e) {
			return new AjaxResult("修改失败");
		}
	}

	/**
	 * @return 添加
	 */
	@SystemControllerLog(description = "添加广告资源")
	@RequestMapping("/addFile")
	@ResponseBody
	public AjaxResult addFile(CaseAdvertiseFile caseAdvertiseFile) {
		CaseAdvertiseFileExample cafe = new CaseAdvertiseFileExample();
		cafe.createCriteria().andCompIdEqualTo(caseAdvertiseFile.getCompId())
				.andNameEqualTo(caseAdvertiseFile.getName());
		List<CaseAdvertiseFile> selectByExample = caseAdvertiseFileMapper.selectByExample(cafe);
		if (selectByExample.isEmpty()) {
			caseAdvertiseFile.setCreatTime(new Date());
			try {
				caseAdvertiseFileMapper.insertSelective(caseAdvertiseFile);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("添加失败");
			}
		} else {
			return new AjaxResult("资源名称重复");
		}
	}

	/**
	 * @return 删除
	 */
	@SystemControllerLog(description = "删除广告资源")
	@RequestMapping("/deleteFile")
	@ResponseBody
	public AjaxResult deleteFile(Integer fileId){
		CaseAdvertiseFile caseAdvertiseFile=new CaseAdvertiseFile();
		caseAdvertiseFile.setFileId(fileId);
		caseAdvertiseFile.setIsDel((byte) 1);
		try {
			caseAdvertiseFileMapper.updateByPrimaryKeySelective(caseAdvertiseFile);
			return new AjaxResult();
		} catch (Exception e) {
			return new AjaxResult("删除失败");
		}

	}

}
